﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using TickSharp.Core.Interfaces;
using TickSharp.Core.Model;

namespace TickSharp.Core.Infrastructure
{
    public class EntryRepository : RepositoryBase
    {
        public EntryRepository(IApiConnectionInfo apiConnectionInfo) : base(apiConnectionInfo)
        {
        }

        /// <summary>
        /// Optional parameters:
        /// project_id
        /// task_id
        /// user_id
        /// user_email
        /// client_id
        /// entry_billable (true|false)
        /// billed (true|false)
        /// 
        /// Required Parameters:
        /// start_date AND end_date
        /// or
        /// updated_at
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Entry> List(DateTime startDate, DateTime endDate)
        {
            string additionalParameters =
                String.Format("start_date={0}&end_date={1}",
                startDate.ToShortDateString(),
                endDate.ToShortDateString());
            string uri = BuildUrl("entries", additionalParameters);

            XElement elements = GetResponse(uri);

            var entries = from e in elements.Elements()
                          where e.Name.LocalName == "entry"
                          select new Entry
                                     {
                                         Id = int.Parse(e.Element("id").Value),
                                         UserId = int.Parse(e.Element("user_id").Value),
                                         Date = DateTime.Parse(e.Element("date").Value),
                                         Hours = float.Parse(e.Element("hours").Value),
                                         Notes = e.Element("notes").Value,
                                         Billable = bool.Parse(e.Element("billable").Value)
                                     };
            return entries;
        }
    }
}
